package com.fable.base;

import com.fable.base.ComponentException.ErrCode;

public final class EnumCodes {

    private EnumCodes() {

    }

    /**
     * 根据枚举类编码获取对应的枚举类
     *
     * @param <E>
     * @param enumClass
     * @param code
     * @return
     */
    public static <E extends EnumCode<?>> E valueOf(Class<E> enumClass, Object code) {
        for (E enumeration : enumClass.getEnumConstants()) {
            if (code == null) {
                throw new ComponentException(ErrCode.参数非法);
            }
            // String
            if (code instanceof String && ((String) enumeration.code()).equalsIgnoreCase((String) code)) {
                return enumeration;
            }
            // Integer
            if (code instanceof Integer && enumeration.code().equals((Integer) code)) {
                return enumeration;
            }

        }

        StringBuilder sb = new StringBuilder();
        sb.append("non-existing code [");
        sb.append(code);
        sb.append("] in enum type [");
        sb.append(enumClass.getName());
        sb.append("]");
        //throw new IllegalArgumentException(sb.toString());
        throw new ComponentException(ErrCode.参数非法, sb.toString());
    }
}
